Golang : Set or add headers for many or different handlers
Problem :
In Golang, setting headers can be done easily with the Set() method.
At the moment, you are setting headers for each individual handler in such as manner :
func handlerA(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler B."))
}
Instead of setting header for each individual handler manually, you want to use a function to set the headers.
NOTE : This method can apply to Add headers as well
Solution :
Create a common SetHeaders()
function that will write to http.ResponseWriter. For example :
func SetHeaders(w http.ResponseWriter) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
}
func handlerA(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler B."))
}
See also : Golang : How to Set or Add Header http.ResponseWriter?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+36.3k Golang : Convert(cast) int64 to string
+11.7k How to tell if a binary(executable) file or web application is built with Golang?
+46.2k Golang : Read tab delimited file with encoding/csv package
+7k Golang : Levenshtein distance example
+7.7k Golang : Command line ticker to show work in progress
+6.5k Golang : Calculate diameter, circumference, area, sphere surface and volume
+31.6k Golang : Get local IP and MAC address
+4.3k Javascript : How to show different content with noscript?
+9.4k Facebook : Getting the friends list with PHP return JSON format
+10.4k Golang : Meaning of omitempty in struct's field tag
+8.4k Golang : Convert word to its plural form example
+5.6k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)